"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const maishu_chitu_service_1 = require("maishu-chitu-service");
const xmljs = require("xml-js");
const node_fetch_1 = require("node-fetch");
const errors_1 = require("./errors");
const SUCCESS_NUM = 0;
const SUCCESS_STR = "SUCCESS";
var service = new maishu_chitu_service_1.Service();
class WeiXinRequest {
    static async get(url, args) {
        let r = await service.get(url, args);
        let err = r;
        if (err.errcode != null && err.errcode != SUCCESS_NUM) {
            let error = { name: `${err.errcode}`, message: err.errmsg };
            return Promise.reject(error);
        }
        return r;
    }
    static async postByXML(url, args) {
        args = args || {};
        var options = { compact: true };
        let xml = xmljs.json2xml(JSON.stringify(args), options);
        let body = `<xml>${xml}</xml>`;
        return node_fetch_1.default(url, { body, method: "post" })
            .then(r => {
            return r.text();
        })
            .then(text => {
            let isXML = text.startsWith("<xml>") && text.endsWith("</xml>");
            if (!isXML) {
                return Promise.resolve(text);
            }
            // let json: string = xmljs.xml2json(text, { compact: true });
            // let obj = JSON.parse(json);
            // if (obj["xml"] == null)
            //     return Promise.reject(errors.responseFormatError(text))
            // obj = obj["xml"];
            // let names = Object.getOwnPropertyNames(obj);
            // for (let i = 0; i < names.length; i++) {
            //     let name = names[i];
            //     obj[name] = obj[name]["_cdata"] ? obj[name]["_cdata"] : obj[name];
            // }
            let obj = parseXMLToJSON(text);
            if (obj.return_code != SUCCESS_STR) {
                // console.log("=========================================")
                // console.log(obj)
                // console.log("=========================================")
                let err = { name: obj.return_code || "unknown", message: obj.return_msg || obj.retmsg || "unknown" };
                return Promise.reject(err);
            }
            return obj;
        });
    }
}
exports.WeiXinRequest = WeiXinRequest;
function parseXMLToJSON(xml) {
    let json = xmljs.xml2json(xml, { compact: true });
    let obj = JSON.parse(json);
    if (obj["xml"] == null)
        return Promise.reject(errors_1.errors.responseFormatError(xml));
    obj = obj["xml"];
    let names = Object.getOwnPropertyNames(obj);
    for (let i = 0; i < names.length; i++) {
        let name = names[i];
        obj[name] = obj[name]["_cdata"] ? obj[name]["_cdata"] : obj[name];
    }
    return obj;
}
exports.parseXMLToJSON = parseXMLToJSON;
